<template>
  <div class="add-equipment">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2 class="page-title">设备档案</h2>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <el-form
        ref="equipmentForm"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="equipment-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <div class="form-row">
            <div class="form-col">
              <el-form-item label="小区" prop="communityId" required>
                <el-select
                  v-model="formData.communityId"
                  placeholder="请选择小区"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="community in communityList"
                    :key="community.communityId"
                    :label="community.communityName"
                    :value="community.communityId"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="安装地点" prop="installationLocation">
                <el-input
                  v-model="formData.installationLocation"
                  placeholder="请输入安装地点"
                />
              </el-form-item>
              
              <el-form-item label="设备名称" prop="equipmentName" required>
                <el-input
                  v-model="formData.equipmentName"
                  placeholder="请输入设备名称"
                />
              </el-form-item>
              
              <el-form-item label="设备类型" prop="equipmentCategory" required>
                <el-select
                  v-model="formData.equipmentCategory"
                  placeholder="请选择设备类型"
                  style="width: 100%"
                >
                  <el-option label="电梯" :value="1" />
                  <el-option label="空调" :value="2" />
                  <el-option label="消防设备" :value="3" />
                  <el-option label="照明设备" :value="4" />
                  <el-option label="给排水设备" :value="5" />
                  <el-option label="安防设备" :value="6" />
                  <el-option label="广告设备" :value="7" />
                  <el-option label="其他设备" :value="8" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="设备编码" prop="equipmentCode" required>
                <el-input
                  v-model="formData.equipmentCode"
                  placeholder="请输入规格编码"
                />
              </el-form-item>
            </div>
            
            <div class="form-col">
              <el-form-item label="规格型号" prop="equipmentSpecification">
                <el-input
                  v-model="formData.equipmentSpecification"
                  placeholder="请输入规格型号"
                />
              </el-form-item>
              
              <el-form-item label="设备状态">
                <el-input
                  value="正常"
                  readonly
                  style="background-color: #f5f7fa;"
                />
              </el-form-item>
              
              <el-form-item label="保养周期" prop="maintenancePeriod">
                <el-select
                  v-model="formData.maintenancePeriod"
                  placeholder="--请选择保养周期--"
                  style="width: 100%"
                  clearable
                >
                  <el-option label="每月" :value="1" />
                  <el-option label="每季度" :value="3" />
                  <el-option label="每半年" :value="6" />
                  <el-option label="每年" :value="12" />
                  <el-option label="每两年" :value="24" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="材料" prop="material">
                <el-input
                  v-model="formData.material"
                  placeholder="请输入材料"
                />
              </el-form-item>
              
              <el-form-item label="重量(KG)" prop="weight">
                <el-input
                  v-model="formData.weight"
                  placeholder="请输入重量"
                  type="number"
                />
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 使用情况 -->
        <div class="form-section">
          <h3 class="section-title">使用情况</h3>
          <div class="form-row">
            <div class="form-col">
              <el-form-item label="安装日期" prop="installationDate">
                <el-date-picker
                  v-model="formData.installationDate"
                  type="date"
                  placeholder="请选择时间"
                  style="width: 100%"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
              
              <el-form-item label="设备原值" prop="equipmentOriginalValue">
                <el-input
                  v-model="formData.equipmentOriginalValue"
                  placeholder="请输入设备原值"
                  type="number"
                />
              </el-form-item>
              
              <el-form-item label="设备净值" prop="equipmentNetValue">
                <el-input
                  v-model="formData.equipmentNetValue"
                  placeholder="请输入设备净值"
                  type="number"
                />
              </el-form-item>
            </div>
            
            <div class="form-col">
              <el-form-item label="报废日期" prop="warrantyDate">
                <el-date-picker
                  v-model="formData.warrantyDate"
                  type="date"
                  placeholder="请选择时间"
                  style="width: 100%"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
              
              <el-form-item label="已提旧值" prop="accumulatedDepreciation">
                <el-input
                  v-model="formData.accumulatedDepreciation"
                  placeholder="请输入已提旧值"
                  type="number"
                />
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 维保单位 -->
        <div class="form-section">
          <h3 class="section-title">维保单位</h3>
          <div class="form-row">
            <div class="form-col">
              <el-form-item label="维保单位" prop="maintenanceUnit">
                <el-input
                  v-model="formData.maintenanceUnit"
                  placeholder="请输入维保单位"
                />
              </el-form-item>
              
              <el-form-item label="维保单位地址" prop="maintenanceAddress">
                <el-input
                  v-model="formData.maintenanceAddress"
                  placeholder="请输入维保单位地址"
                />
              </el-form-item>
              
              <el-form-item label="生产厂家" prop="manufacturer">
                <el-input
                  v-model="formData.manufacturer"
                  placeholder="请输入生产厂家"
                />
              </el-form-item>
              
              <el-form-item label="厂家地址" prop="manufacturerAddress">
                <el-input
                  v-model="formData.manufacturerAddress"
                  placeholder="请输入厂家地址"
                />
              </el-form-item>
            </div>
            
            <div class="form-col">
              <el-form-item label="维保单位电话" prop="maintenancePhone">
                <el-input
                  v-model="formData.maintenancePhone"
                  placeholder="请输入维保单位电话"
                />
              </el-form-item>
              
              <el-form-item label="设备维保人" prop="equipmentMaintainer">
                <el-input
                  v-model="formData.equipmentMaintainer"
                  placeholder="请输入维保人"
                />
              </el-form-item>
              
              <el-form-item label="厂家电话" prop="manufacturerPhone">
                <el-input
                  v-model="formData.manufacturerPhone"
                  placeholder="请输入厂家电话"
                  style="width: 100%"
                />
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 其他信息 -->
        <div class="form-section">
          <div class="form-row">
            <div class="form-col">
              <el-form-item label="登记日期" prop="registrationDate">
                <el-input
                  v-model="formData.registrationDate"
                  placeholder="请输入小区/设备名称/设备编码"
                  readonly
                />
              </el-form-item>
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-col full-width">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-model="formData.remarks"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="success" @click="handleSubmit" :loading="submitting">
            保存
          </el-button>
          <el-button @click="handleCancel">
            取消
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { equipmentApi } from '@/api/equipment'
import request, { communityRequest } from '@/utils/request'

export default {
  name: 'AddEquipment',
  data() {
    return {
      // 表单数据
      formData: {
        communityId: '',
        installationLocation: '',
        equipmentName: '',
        equipmentCategory: null,
        equipmentCode: '',
        equipmentSpecification: '',
        equipmentStatus: 1, // 默认正常状态
        maintenancePeriod: null,
        material: '',
        weight: null,
        installationDate: '',
        warrantyDate: '',
        equipmentOriginalValue: null,
        accumulatedDepreciation: null,
        equipmentNetValue: null,
        maintenanceUnit: '',
        maintenancePhone: '',
        maintenanceAddress: '',
        equipmentMaintainer: '',
        manufacturer: '',
        manufacturerPhone: '',
        manufacturerAddress: '',
        registrationDate: '',
        maintenanceNum: 0,
        repairNum: 0,
        remarks: ''
      },
      
      // 表单验证规则
      formRules: {
        communityId: [
          { required: true, message: '请选择小区', trigger: 'change' }
        ],
        equipmentName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ],
        equipmentCategory: [
          { required: true, message: '请选择设备类型', trigger: 'change' }
        ],
        equipmentCode: [
          { required: true, message: '请输入设备编码', trigger: 'blur' }
        ]
      },
      
      // 小区列表
      communityList: [],
      
      // 提交状态
      submitting: false
    }
  },
  
  mounted() {
    this.loadCommunityList()
    this.setRegistrationDate()
  },
  
  methods: {
    // 加载小区列表
    async loadCommunityList() {
      try {
        const response = await communityRequest({
          url: '/community/selcomm',
          method: 'get'
        })
        if (response.code === 200) {
          this.communityList = response.data || []
        } else {
          this.$message.error(response.message || '加载小区列表失败')
        }
      } catch (error) {
        console.error('加载小区列表失败:', error)
        this.$message.error('加载小区列表失败')
      }
    },
    
    // 设置登记日期为当前日期
    setRegistrationDate() {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      this.formData.registrationDate = `${year}-${month}-${day}`
      console.log('设置登记日期:', this.formData.registrationDate) // 调试用
    },
    
    // 提交表单
    async handleSubmit() {
      try {
        // 表单验证
        await this.$refs.equipmentForm.validate()
        
        this.submitting = true
        
        // 准备提交数据，处理空值
        const submitData = {
          communityId: this.formData.communityId,
          equipmentName: this.formData.equipmentName,
          equipmentCategory: this.formData.equipmentCategory,
          equipmentCode: this.formData.equipmentCode,
          equipmentStatus: 1, // 新增设备默认为正常状态
          maintenanceNum: 0,  // 新增设备保养次数为0
          repairNum: 0,       // 新增设备维修次数为0
          // 处理日期字段，空字符串转为null
          installationDate: this.formData.installationDate && this.formData.installationDate.trim() !== '' ? this.formData.installationDate : null,
          warrantyDate: this.formData.warrantyDate && this.formData.warrantyDate.trim() !== '' ? this.formData.warrantyDate : null,
          registrationDate: this.formData.registrationDate && this.formData.registrationDate.trim() !== '' ? this.formData.registrationDate : null,
          // 处理数值字段，空字符串转为null
          weight: this.formData.weight && this.formData.weight.toString().trim() !== '' ? Number(this.formData.weight) : null,
          equipmentOriginalValue: this.formData.equipmentOriginalValue && this.formData.equipmentOriginalValue.toString().trim() !== '' ? Number(this.formData.equipmentOriginalValue) : null,
          accumulatedDepreciation: this.formData.accumulatedDepreciation && this.formData.accumulatedDepreciation.toString().trim() !== '' ? Number(this.formData.accumulatedDepreciation) : null,
          equipmentNetValue: this.formData.equipmentNetValue && this.formData.equipmentNetValue.toString().trim() !== '' ? Number(this.formData.equipmentNetValue) : null,
          // 处理字符串字段，空字符串转为null
          installationLocation: this.formData.installationLocation && this.formData.installationLocation.trim() !== '' ? this.formData.installationLocation : null,
          equipmentSpecification: this.formData.equipmentSpecification && this.formData.equipmentSpecification.trim() !== '' ? this.formData.equipmentSpecification : null,
          material: this.formData.material && this.formData.material.trim() !== '' ? this.formData.material : null,
          maintenancePeriod: this.formData.maintenancePeriod,
          maintenanceUnit: this.formData.maintenanceUnit && this.formData.maintenanceUnit.trim() !== '' ? this.formData.maintenanceUnit : null,
          maintenancePhone: this.formData.maintenancePhone && this.formData.maintenancePhone.trim() !== '' ? this.formData.maintenancePhone : null,
          maintenanceAddress: this.formData.maintenanceAddress && this.formData.maintenanceAddress.trim() !== '' ? this.formData.maintenanceAddress : null,
          equipmentMaintainer: this.formData.equipmentMaintainer && this.formData.equipmentMaintainer.trim() !== '' ? this.formData.equipmentMaintainer : null,
          manufacturer: this.formData.manufacturer && this.formData.manufacturer.trim() !== '' ? this.formData.manufacturer : null,
          manufacturerPhone: this.formData.manufacturerPhone && this.formData.manufacturerPhone.trim() !== '' ? this.formData.manufacturerPhone : null,
          manufacturerAddress: this.formData.manufacturerAddress && this.formData.manufacturerAddress.trim() !== '' ? this.formData.manufacturerAddress : null,
          remarks: this.formData.remarks && this.formData.remarks.trim() !== '' ? this.formData.remarks : null
        }
        
        console.log('提交数据:', submitData) // 调试用
        
        const response = await equipmentApi.addEquipment(submitData)
        if (response.code === 200) {
          this.$message.success('设备添加成功')
          this.$router.go(-1) // 返回上一页
        } else {
          this.$message.error(response.message || '设备添加失败')
        }
      } catch (error) {
        if (error.message) {
          // 表单验证错误
          return
        }
        console.error('提交失败:', error)
        this.$message.error('设备添加失败')
      } finally {
        this.submitting = false
      }
    },
    
    // 取消操作
    handleCancel() {
      this.$router.go(-1) // 返回上一页
    }
  }
}
</script>

<style scoped>
.add-equipment {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.form-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.equipment-form {
  max-width: 1200px;
  margin: 0 auto;
}

.form-section {
  margin-bottom: 40px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
}

.form-row {
  display: flex;
  gap: 40px;
  margin-bottom: 20px;
}

.form-col {
  flex: 1;
}

.form-col.full-width {
  flex: 2;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.form-actions .el-button {
  min-width: 100px;
  height: 40px;
}

/* 表单项样式调整 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-textarea__inner) {
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-equipment {
    padding: 10px;
  }
  
  .form-container {
    padding: 20px;
  }
  
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .form-col {
    margin-bottom: 20px;
  }
  
  .form-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .form-actions .el-button {
    width: 200px;
  }
}
</style>
